package org.smartboot.compare.comparator;

import org.smartboot.compare.Accessor;
import org.smartboot.compare.Option;
import org.smartboot.compare.constants.CompareConstants;
import org.smartboot.compare.utils.InternalClassUtils;

import java.util.List;

/**
 * @author qinluo
 * @date 2024-06-08 18:18:40
 * @since 1.1.0
 */
public class ListAccessor implements Accessor {

    private final List<?> source;

    public ListAccessor(List<?> source) {
        this.source = source;
    }

    @Override
    public int getLength() {
        return source != null ? source.size() : 0;
    }

    @Override
    public Object elementAt(int index) {
        return source.get(index);
    }

    @Override
    public Object getSource() {
        return source;
    }

    @Override
    public boolean supportOption(Option option) {
        if (option == Option.TRANS_AS_SET) {
            return isSimpleContainer(source);
        }

        return false;
    }

    @Override
    public int getSourceType() {
        return CompareConstants.LIST;
    }

    private boolean isSimpleContainer(List<?> list) {
        if (list == null || list.isEmpty()) {
            return true;
        }

        for (Object value : list) {
            if (value == null) {
                continue;
            }

            Class<?> type = value.getClass();
            if (type == String.class || InternalClassUtils.isSimple(type)) {
                continue;
            }

            return false;
        }

        return true;
    }
}
